# -*- coding: utf-8 -*-

from .base import BaseClient

try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode

import json
import time

import requests


class Client(BaseClient):
    def __init__(self, client_id, client_secret, redirect_uri, token=None):
        # const define
        self.windowName = ''
        self.provider = 'weibo'
        self.authorization_url = 'https://api.weibo.com/oauth2/authorize'
        self.grant_url = 'https://api.weibo.com/oauth2/access_token'
        self.api_url = 'https://api.weibo.com/2/'
        self.response_type = 'code'
        self.grant_type = 'authorization_code'
        # init basic info
        self.client_id = client_id
        self.client_secret = client_secret
        self.redirect_uri = redirect_uri

        # client scope
        self.scope = {
            'all': 'all',  # 请求下列所有scope权限
            'email': 'email',  # 用户的联系邮箱
            'direct_messages_write': 'direct_messages_write',  # 私信发送接口
            'direct_messages_read': 'direct_messages_read',  # 私信读取接口
            'invitation_write': 'invitation_write',  # 邀请发送接口
            'friendships_groups_read': 'friendships_groups_read',  # 好友分组读取接口组
            'friendships_groups_write': 'friendships_groups_write',  # 好友分组写入接口组
            'statuses_to_me_read': 'statuses_to_me_read',  # 定向微博读取接口组
            'follow_app_official_microblog': 'follow_app_official_microblog'
            # 关注应用官方微博，该参数不对应具体接口，只需在应用控制台填写官方帐号即可。填写的路径：我的应用-选择自己的应用-应用信息-基本信息-官方运营账号（默认值是应用开发者帐号）
        }

        # activate client directly if given token
        if token:
            self.set_token(token)

    def set_code(self, authorization_code):
        """Activate client by authorization_code.
        """
        params = {
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'grant_type': 'authorization_code',
            'code': authorization_code,
            'redirect_uri': self.redirect_uri
        }
        res = requests.post(self.token_url, data=params)
        token = json.loads(res.text)
        self._assert_error(token)

        token[u'expires_at'] = int(time.time()) + int(token.pop(u'expires_in'))
        self.set_token(token)



    def _assert_error(self, d):
        """Assert if json response is error.
        """
        if 'error_code' in d and 'error' in d:
            raise RuntimeError("{0} {1}".format(
                d.get("error_code", ""), d.get("error", "")))

    def get(self, uri, **kwargs):
        """Request resource by get method.
        """
        url = "{0}{1}".format(self.api_url, uri)

        # for username/password client auth
        if self.session.auth:
            kwargs['source'] = self.client_id

        res = json.loads(self.session.get(url, params=kwargs).text)
        self._assert_error(res)
        return res

    def post(self, uri, **kwargs):
        """Request resource by post method.
        """
        url = "{0}{1}.json".format(self.api_url, uri)

        if "pic" not in kwargs:
            res = json.loads(self.session.post(url, data=kwargs).text)
        else:
            files = {"pic": kwargs.pop("pic")}
            res = json.loads(self.session.post(url,
                                               data=kwargs,
                                               files=files).text)
        self._assert_error(res)
        return res
